import os
import argparse

from device import Device
from openpyxl import load_workbook
from PIL import Image, ImageDraw, ImageFont
from resident import Resident, parse_sheet


def current_path() -> str:
    return os.path.split(os.path.realpath(__file__))[0]


def mark_image(input_image: str, output_image: str, text: str):
    """
    将文字打到二维码截图上
    """
    src_img = Image.open(input_image)
    width = src_img.size[0]
    height = src_img.size[1]
    cropped = src_img.crop((0, 240, width, 240+1000))
    cropped.convert('RGB').save('cropped.jpg')

    cropped_img = Image.open('cropped.jpg')
    draw = ImageDraw.Draw(cropped_img)
    size = 85
    # 本人的Kubuntu 22.04上使用此字体
    # style = '/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc' 
    # 此处使用网上下下来的微软雅黑字体，不知是否有版权问题
    style = 'SimHei.ttf' 
    font = ImageFont.truetype(style, size)
    draw.text((400, 20), text, (0, 0, 0), font=font)
    cropped_img.save(output_image)


def prepare_hierachy(root: str):
    root_dir = os.path.join(current_path(), root)
    raw_dir = os.path.join(root_dir, 'raw')
    pic_dir = os.path.join(root_dir, 'picture')
    err_dir = os.path.join(root_dir, 'error')
    if not os.path.exists(root_dir):
        os.mkdir(root_dir)

    if not os.path.exists(raw_dir):
        os.mkdir(raw_dir)

    if not os.path.exists(pic_dir):
        os.mkdir(pic_dir)
    
    if not os.path.exists(err_dir):
        os.mkdir(err_dir)


def prepare_building_dir(root: str, resident: Resident):
    root_dir = os.path.join(current_path(), root)
    raw_building_dir = os.path.join(root_dir, 'raw', resident.building)
    pic_building_dir = os.path.join(root_dir, 'picture', resident.building)
    err_building_dir = os.path.join(root_dir, 'error', resident.building)

    if not os.path.exists(raw_building_dir):
        os.mkdir(raw_building_dir)

    if not os.path.exists(pic_building_dir):
        os.mkdir(pic_building_dir)
    
    if not os.path.exists(err_building_dir):
        os.mkdir(err_building_dir)


def get_raw_path(root: str, resident: Resident) -> str:
    root_dir = os.path.join(current_path(), root)
    raw_building_dir = os.path.join(root_dir, 'raw', resident.building, f'{resident.name}-{resident.building}-{resident.room}.jpg')
    return raw_building_dir


def get_picture_path(root: str, resident: Resident) -> str:
    root_dir = os.path.join(current_path(), root)
    pic_building_dir = os.path.join(root_dir, 'picture', resident.building, f'{resident.name}-{resident.building}-{resident.room}.jpg')
    return pic_building_dir


def get_error_path(root: str, resident: Resident) -> str:
    root_dir = os.path.join(current_path(), root)
    error_building_dir = os.path.join(root_dir, 'error', resident.building, f'{resident.name}-{resident.building}-{resident.room}.jpg')
    return error_building_dir


def resident_is_registered(root: str, resident: Resident) -> bool:
    return os.path.exists(get_picture_path(root, resident))


def resident_is_error(root: str, resident: Resident) -> bool:
    return os.path.exists(get_error_path(root, resident))


def register_resident(resident: Resident, device: Device):
    return device.register_info(resident.id_no, resident.name, resident.phone_no, f'{resident.building}号{resident.room}', '江凌苑')


def should_skip(root: str, resident: Resident, max_age: int)-> bool:
    if resident_is_error(root, resident) or resident_is_registered(root, resident) or (resident.age <= max_age):
        return True

    return False


def main(xls_file: str, root: str, building_to_register: str, max_age: int = 58):
    
    prepare_hierachy(root)

    wb = load_workbook(xls_file, data_only=True)
    with open(os.path.join(current_path(), root, 'invalid_info.txt'), 'w', encoding='utf8') as f:
        device = Device('PYB0220917001570', '10')
        device.enter_register_ui()
        for sheet in wb:
            ret = parse_sheet(sheet)
            if not ret:
                continue
            residents, invalid_residents = ret

            if residents[0].building != building_to_register:
                continue


            for invalid in invalid_residents:
                f.write(invalid)
                f.write('\n')
            prepare_building_dir(root, residents[0])

            for resident in residents:
                if should_skip(root, resident, max_age):
                    continue
                else:
                    print(f'register {resident}({resident.building}-{resident.room})')
                    
                    try:
                        success = register_resident(resident, device)
                        if success:
                            device.screenshot(get_raw_path(root, resident))
                            mark_image(get_raw_path(root, resident), get_picture_path(root, resident), f'{resident.building}-{resident.room}')
                        else:
                            device.screenshot(get_error_path(root, resident))
                    except Exception as e:
                        print(f'register exception: {e}')
                    finally:
                        pass
                    

if __name__ == '__main__':
    parser = argparse.ArgumentParser('')
    parser.add_argument('-f', type=str) # 生成结果的根目录
    parser.add_argument('-x', type=str) # Excel文件路径
    parser.add_argument('-b', type=str) # 楼号
    args = parser.parse_args()
    root = args.f
    xls_file = args.x
    building = args.b

    main(xls_file, root, building)

    
# 38,39,40,41